﻿
namespace MMSSync.Helpers
{
    using Entities;
    using Microsoft.SharePoint.Client.Taxonomy;
    using System.Collections.Generic;
    #region Imports

    using System.Windows.Forms;
    using System.Xml;
    #endregion

    /// <summary>
    /// Helper class to serialize Tree to XML
    /// </summary>
    class TreeToXMLSerializer
    {
        private const string XmlNodeTermSet = "TermSet";
        private const string XmlNodeTerm = "Term";
        private const string XmlNodeNameAtt = "Name";
        private const string XmlNodeTagAtt = "Tag";
        private const string XmlNodeIdAtt = "Id";

        public void SerializeToXML(TreeNodeCollection nodes, KeyValuePair<string, string> kvGroup, string fileName)
        {
            XmlTextWriter textWriter = new XmlTextWriter(fileName, System.Text.Encoding.ASCII);
            // writing the xml declaration tag
            textWriter.WriteStartDocument();
            
            // Write TermStore Start Tag
            textWriter.WriteStartElement("TermStore");
            // Write TermSetGroup Start Tag
            textWriter.WriteStartElement("TermSetGroup");
            textWriter.WriteAttributeString(XmlNodeNameAtt, kvGroup.Value);
            textWriter.WriteAttributeString(XmlNodeIdAtt, kvGroup.Key);
            // Write first node as TermSet node
            TreeNodeItem parent = (TreeNodeItem)nodes[0];
            textWriter.WriteStartElement("TermSet");
            textWriter.WriteAttributeString(XmlNodeNameAtt, parent.Text);
            textWriter.WriteAttributeString(XmlNodeIdAtt, parent.TermGuid.ToString());

            // save the nodes, recursive method
            SaveNodes(parent.Nodes, textWriter);

            // Write End Tag for TermStore and TermSet
            textWriter.WriteEndElement();
            textWriter.WriteEndElement();
            textWriter.WriteEndElement();
            textWriter.Close();
        }

        private void SaveNodes(TreeNodeCollection nodes, XmlTextWriter textWriter)
        {
            for (int i = 0; i < nodes.Count; i++)
            {
                TreeNodeItem node = (TreeNodeItem)nodes[i];
                textWriter.WriteStartElement(XmlNodeTerm);
                textWriter.WriteAttributeString(XmlNodeNameAtt, node.Text);
                textWriter.WriteAttributeString(XmlNodeIdAtt, node.TermGuid.ToString());
                //if (node.Tag != null)
                //    textWriter.WriteAttributeString(XmlNodeTagAtt, node.Tag.ToString());
                // add other node properties to serialize here  
                if (node.Nodes.Count > 0)
                {
                    SaveNodes(node.Nodes, textWriter);
                }
                textWriter.WriteEndElement();
            }
        }
    }
}
